import { BrowserWindow, ipcMain, screen } from 'electron'
// 自定义窗口拖动
let movingInterval = null
ipcMain.handle('drag', (event, canMoving) => {
  const currentWindow = BrowserWindow.getFocusedWindow()
  let winStartPosition = { x: 0, y: 0 }
  let mouseStartPosition = { x: 0, y: 0 }
  // 获取当前聚焦的窗口
  if (currentWindow) {
    if (canMoving) {
      // 读取原位置
      let winPosition = currentWindow.getPosition()
      winStartPosition = { x: winPosition[0], y: winPosition[1] }
      mouseStartPosition = screen.getCursorScreenPoint()
      // 清除旧的定时器
      if (movingInterval) {
        clearInterval(movingInterval)
      }
      // 创建定时器，每10毫秒更新一次窗口位置，保证一致
      movingInterval = setInterval(() => {
        // 窗口销毁判断，高频率的更新有可能窗口已销毁，定时器还没结束，此时就会出现执行销毁窗口方法的错误
        if (!currentWindow.isDestroyed()) {
          let currentWindowSize = currentWindow.getSize()
          // 如果窗口失去焦点，则停止移动
          if (!currentWindow.isFocused()) {
            clearInterval(movingInterval)
            movingInterval = null
          }
        
          // 实时更新位置
          const cursorPosition = screen.getCursorScreenPoint()
          const x = winStartPosition.x + cursorPosition.x - mouseStartPosition.x
          const y = winStartPosition.y + cursorPosition.y - mouseStartPosition.y
          // 更新位置的同时设置窗口原大小， windows上设置=>显示设置=>文本缩放 不是100%时，窗口会拖拽放大
          currentWindow.setBounds({
            x: x,
            y: y,
            width: currentWindowSize[0],
            height: currentWindowSize[1]
          })
        }
      }, 10)
    } else {
      clearInterval(movingInterval)
      movingInterval = null
    }
  }
})

ipcMain.handle('windowChange', (event, type) => {
  const currentWindow = BrowserWindow.getFocusedWindow()
  const strategy = {
    1: () => {
      currentWindow.minimize()
    },
    2: () => {
      if (currentWindow.isMaximized()) {
        currentWindow.restore()
      } else {
        currentWindow.maximize()
      }
      return currentWindow.isMaximized()
    },
    3: () => {
      currentWindow.hide()
    }
  }
 return strategy[type] && strategy[type]()
})




